<template>
  <div style="display: flex;width: 100%;height: 100%;align-items: center;justify-content: center">

    <el-card class="infoOuterBox box-card">
      <el-form
          ref="userInfoFormRef"
          :model="userInfoForm"
          label-width="26%"
          label-position="left"
          :rules="userInfoFormRules"
          status-icon
          style="padding: 20px;text-align: center"
      >
        <div style="display: flex;justify-items: center;align-items: center;flex-direction: column;">
          <el-avatar style="width: 100px;height: 100px;display: block;margin-bottom: 10px;" :src="userInfoForm.avatar"/>
          <el-upload
              v-if="!editStatus"
              ref="uploadAvatarRef"
              class="upload-demo"
              :limit="1"
              :on-exceed="handleExceed"
              :before-upload="beforeUploadAvatarHandler"
              :auto-upload="false"
              :on-change="changeHandle"
              :on-remove="removeHandle"
          >
            <template #trigger>
              <el-button type="primary" style="margin-right: 7px;">选择头像</el-button>
            </template>
            <el-button @click="submitUpload" :disabled="submitDisabled">
              上传
            </el-button>

          </el-upload>
        </div>
        <el-divider style="margin: 10px 0 ;"/>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfoForm.username" :disabled="editStatus" autocomplete="off" style="width: 230px"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userInfoForm.sex" :disabled="editStatus">
            <el-radio label="男" size="large">男</el-radio>
            <el-radio label="女" size="large">女</el-radio>
            <el-radio label="保密" size="large">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="userInfoForm.age" :disabled="editStatus" :min="1" :max="110"/>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="userInfoForm.phone" :disabled="editStatus" autocomplete="off" style="width: 230px"/>
        </el-form-item>
        <el-divider style="margin: 15px 0 ;"/>
        <div class="buttonBox">
          <el-button v-if="editStatus" @click="switchEditStatus" style="width: 40%">编辑信息</el-button>
          <el-button v-if="!editStatus" @click="switchEditStatus" style="width: 30%">取 消</el-button>
          <el-button v-if="!editStatus" @click="submitEditHandle" type="primary" style="width: 30%">确认修改</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {Avatar, Message} from "@element-plus/icons-vue";
import request from "@/utils/request";
import {ElMessage} from "element-plus";

export default {
  name: "UserCenter",
  components: {Avatar},
  data() {
    return {
      userInfoForm: {
        username: '',
        sex: '',
        age: 0,
        phone: '',
        avatar: ''
      },
      tempForm: undefined,
      userInfoFormRules: {
        username: [{required: true, message: "用户名不能为空", trigger: "blur"}],
        sex: [{required: true, message: "请选择性别", trigger: "blur"}],
        age: [{required: true, message: "请输入年龄", trigger: "blur"}],
        phone: [
          {required: true, message: "请输入电话号码", trigger: "blur"},
          {pattern: /^1[3456789]\d{9}$/, message: "请输入正确的11位手机号码", trigger: "blur"}
        ]
      },
      // true 为阅读模式；false 为编辑模式
      editStatus: true,
      avatarUploadUrl: '',
      submitDisabled: true
    }
  },
  methods: {
    switchEditStatus() {
      if (this.editStatus) {
        //   当前状态为阅读模式点击切换为编辑模式
        this.tempForm = {...this.userInfoForm}
      } else {
        //   当前状态是编辑模式点击取消为阅读模式
        //   将备份的数据赋值会表单
        this.userInfoForm = {...this.tempForm}
        this.$refs.userInfoFormRef.clearValidate()
      }
      this.editStatus = !this.editStatus
    },
    submitEditHandle() {
      this.$refs.userInfoFormRef.validate((isValid) => {
        if (isValid) {
          // 创建一个dto类型的对象用于请求
          let tempDtp = {
            username: this.userInfoForm.username,
            sex: this.userInfoForm.sex,
            age: this.userInfoForm.age,
            phone: this.userInfoForm.phone,
          }
          //   发起修改请求
          request.put('/editUser', tempDtp).then(
              res => {
                console.log(res)
                this.getUserInfo()
                this.$refs.userInfoFormRef.clearValidate()
                this.editStatus = !this.editStatus
                ElMessage({
                  message: '编辑信息成功',
                  type: 'success',
                })

                this.$router.go(0)
              },
              err => {
                console.log(err)
              }
          )
        }
      })
    },
    getUserInfo() {
      //   获取当前用信息
      request.get("/userInfo").then(
          res => {
            this.userInfoForm = res.data
          },
          err => {
            console.log(err)
          }
      )
    },
    handleExceed(files) {
      console.log(files)
      this.$refs.uploadAvatarRef.clearFiles()
      const file = files[0];
      file.uid = Date.now().toString();
      console.log(file)
      this.$refs.uploadAvatarRef.handleStart(file);
    },
    submitUpload() {
      this.$refs.uploadAvatarRef.submit()
    },
    beforeUploadAvatarHandler(file) {
      const formData = new FormData();
      formData.append('file', file);
      request.post("/uploadAvatar", formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(
          res => {
            ElMessage({
              message: "头像上传成功!",
              type: "success"
            })
            this.$router.go(0)
          },
          err => {
            ElMessage({
              message: "头像上传失败, 请检查文件是否正确选择",
              type: "error"
            })
          })
      return false;
    },
    changeHandle(f, fs) {
      this.submitDisabled = false
    },
    removeHandle(f, fs) {
      this.submitDisabled = true
    }
  },
  mounted() {
    this.getUserInfo()
    // 注入父路由中的方法

  }

}
</script>

<style>
.infoOuterBox {
  padding: 0 !important;
}
</style>